from flask import Flask, request, jsonify, render_template
from flask_cors import CORS
import json
import logging
from scrapers.jd_scraper import JDScraper
from scrapers.taobao_scraper import TaobaoScraper
from scrapers.dewu_scraper import DewuScraper
from utils.price_analyzer import PriceAnalyzer

app = Flask(__name__, template_folder='../templates', static_folder='../static')
CORS(app)

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/api/search', methods=['POST'])
def search_products():
    try:
        data = request.get_json()
        brand = data.get('brand', '').strip()
        sku = data.get('sku', '').strip()
        
        if not brand or not sku:
            return jsonify({
                'success': False,
                'message': '品牌和货号不能为空'
            }), 400
        
        # 搜索关键词
        keyword = f"{brand} {sku}"
        logger.info(f"开始搜索: {keyword}")
        
        # 初始化爬虫
        scrapers = {
            'jd': JDScraper(),
            'taobao': TaobaoScraper(),
            'dewu': DewuScraper()
        }
        
        # 收集所有平台数据
        all_products = []
        platform_data = []
        
        for platform_name, scraper in scrapers.items():
            try:
                products = scraper.search(keyword)
                if products:
                    prices = [p['price'] for p in products]
                    platform_info = {
                        'name': platform_name,
                        'displayName': get_platform_display_name(platform_name),
                        'products': products,
                        'priceRange': {
                            'min': min(prices),
                            'max': max(prices)
                        }
                    }
                    platform_data.append(platform_info)
                    all_products.extend(products)
                    logger.info(f"{platform_name} 找到 {len(products)} 个商品")
                else:
                    logger.warning(f"{platform_name} 未找到商品")
            except Exception as e:
                logger.error(f"{platform_name} 爬取失败: {str(e)}")
                # 继续处理其他平台
        
        if not all_products:
            return jsonify({
                'success': False,
                'message': '未找到相关商品，请检查品牌和货号是否正确'
            }), 404
        
        # 价格分析
        analyzer = PriceAnalyzer()
        price_analysis = analyzer.analyze(all_products)
        
        response_data = {
            'success': True,
            'keyword': keyword,
            'platforms': platform_data,
            'priceRange': {
                'min': price_analysis['min_price'],
                'max': price_analysis['max_price'],
                'avg': price_analysis['avg_price']
            },
            'suggestedPrice': price_analysis['suggested_price'],
            'totalProducts': len(all_products)
        }
        
        logger.info(f"搜索完成，共找到 {len(all_products)} 个商品")
        return jsonify(response_data)
        
    except Exception as e:
        logger.error(f"搜索过程出错: {str(e)}")
        return jsonify({
            'success': False,
            'message': '服务器内部错误，请稍后重试'
        }), 500

def get_platform_display_name(platform):
    names = {
        'jd': '京东',
        'taobao': '淘宝',
        'dewu': '得物'
    }
    return names.get(platform, platform)

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=5000)
